/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.kth.lwr.jeat.core;

import java.util.HashSet;
import java.util.Set;
import javax.measure.quantity.Quantity;
import javax.measure.unit.NonSI;
import javax.measure.unit.ProductUnit;
import javax.measure.unit.SI;
import javax.measure.unit.Unit;
import org.jscience.physics.amount.Amount;
import se.kth.lwr.jeat.samples.onsitetreatment.Units;

/**
 *
 * @author davidev
 */
/**The UnitHandler is the default way of manipulating units in {@link Report}s.
 * It compares passed Unit to a list of preferred Units and make conversions if 
 * possible.
 */
public class DefaultUnitHandler implements UnitHandler {
    //stores a bunch of units that is prefered to view
    Set<Unit<? extends Quantity>> prefUnits = new HashSet<>();
 
    public DefaultUnitHandler() {

        //Some global standards... not
        prefUnits.add(SI.MEGA(SI.JOULE).divide(SI.KILOGRAM));
        prefUnits.add(SI.MEGA(SI.JOULE).divide(NonSI.YEAR));
        prefUnits.add(SI.KILOGRAM);
        
        //...
        //...
    }

    /**
     * adds a preferred Unit
     *
     * @param u a preferred Unit
     */
    public void addPreferedUnit(Unit<? extends Quantity> u) {
        prefUnits.add(u);
    }

    /**
     * try to remove a prefered Unit
     *
     * @param u a Unit to remove
     */
    public void removePreferedUnit(Unit u) {
        prefUnits.remove(u);
    }

    /**
     * Returns the amount in a preferred Unit if possible. Otherwise leaves the
     * argument untouched
     *
     * @param amount the amount that we should try to convert to a preferred
     * unit
     * @return an Amount with a preferred unit or the argument untouched
     */
    @Override
    public Amount toPreferedUnit(Amount<? extends Quantity> amount) {
        for (Unit<? extends Quantity> u : prefUnits) {            
            if (amount.getUnit().isCompatible(u)) {
                return amount.to(u);
            }             
        }
        return amount;
    }
    
}
